<template>
  <v-sheet class="pa-8" rounded="lg" elevation="3">
    <v-tabs v-model="tab" centered>
      <v-tabs-slider></v-tabs-slider>
      <v-tab class="my-tab-style" href="#tab-1"> 登录 </v-tab>
      <v-tab class="my-tab-style" href="#tab-2"> 注册 </v-tab>
    </v-tabs>

    <v-tabs-items v-model="tab">
      <!-- 登录 -->
      <v-tab-item :value="'tab-1'">
        <v-row justify="center" class="ma-0">
          <v-col class="col-4">
            <v-card flat class="mt-3">
              <form @submit.prevent="login_form">
                <!-- 用户名 -->
                <v-text-field
                  v-model="form.username"
                  label="用户名"
                  required
                ></v-text-field>
                <!-- 密码 -->
                <v-text-field
                  v-model="form.password"
                  type="password"
                  label="密码"
                  required
                ></v-text-field>
                <!-- 错误信息 -->
                <v-alert
                  v-if="error.login.showError"
                  class="mt-3"
                  dense
                  outlined
                  type="error"
                >
                  {{ error.login.errorMsg }}
                </v-alert>
                <!-- 登录按钮 -->
                <v-row justify="center" class="ma-0">
                  <v-col class="mt-2 pb-0 px-0 col-12">
                    <v-btn
                      class="mr-4 white--text"
                      type="submit"
                      color="blue"
                      block
                    >
                      登录
                    </v-btn>
                  </v-col>
                </v-row>
              </form>
            </v-card>
          </v-col>
        </v-row>
      </v-tab-item>
      <!-- 注册 -->
      <v-tab-item :value="'tab-2'">
        <v-row justify="center" class="ma-0">
          <v-col class="col-4">
            <v-card flat class="mt-3">
              <validation-observer ref="observer" v-slot="{ invalid }">
                <form @submit.prevent="register_form">
                  <!-- 用户名 -->
                  <validation-provider
                    v-slot="{ errors }"
                    name="用户名"
                    :rules="{
                      required: true,
                      max: 15,
                      regex_username: '^([a-zA-Z])[a-zA-Z0-9]*$',
                    }"
                  >
                    <v-text-field
                      v-model="form.username"
                      :counter="15"
                      :error-messages="errors"
                      label="用户名(只能包含字母和数字，首位只能为字母)"
                      required
                    ></v-text-field>
                  </validation-provider>
                  <!-- 真实姓名 -->
                  <validation-provider
                    v-slot="{ errors }"
                    name="真实姓名"
                    :rules="{
                      required: true,
                      max: 30,
                    }"
                  >
                    <v-text-field
                      v-model="form.full_name"
                      :counter="30"
                      :error-messages="errors"
                      label="真实姓名(方便活动的进行)"
                      required
                    ></v-text-field>
                  </validation-provider>
                  <!-- 邮箱 -->
                  <validation-provider
                    v-slot="{ errors }"
                    name="邮箱"
                    rules="required|email"
                  >
                    <v-text-field
                      v-model="form.email"
                      :error-messages="errors"
                      label="邮箱"
                      required
                    ></v-text-field>
                  </validation-provider>
                  <!-- 学院 -->
                  <validation-provider
                    v-slot="{ errors }"
                    name="学院"
                    rules="required"
                  >
                    <v-select
                      v-model="form.school"
                      :items="form.schools"
                      :error-messages="errors"
                      label="学院"
                      data-vv-name="select"
                      required
                    ></v-select>
                  </validation-provider>
                  <!-- 密码 -->
                  <validation-provider
                    v-slot="{ errors }"
                    name="密码"
                    :rules="{
                      required: true,
                      max: 16,
                      min: 8,
                      regex_password:
                        '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$',
                    }"
                  >
                    <v-text-field
                      v-model="form.password"
                      :append-icon="
                        form.showPassword ? 'mdi-eye' : 'mdi-eye-off'
                      "
                      :type="form.showPassword ? 'text' : 'password'"
                      label="密码(必须且只能包含字母和数字)"
                      hint="密码为8到16位"
                      :error-messages="errors"
                      counter="16"
                      @click:append="form.showPassword = !form.showPassword"
                    ></v-text-field>
                  </validation-provider>
                  <!-- 错误信息 -->
                  <v-alert
                    v-if="error.register.showError"
                    class="mt-3"
                    dense
                    outlined
                    type="error"
                  >
                    {{ error.register.errorMsg }}
                  </v-alert>
                  <!-- 登录和注册按钮 -->
                  <v-row justify="center" class="ma-0">
                    <div class="mt-2">
                      <v-btn
                        class="mr-4 white--text"
                        type="submit"
                        :disabled="invalid"
                        color="blue"
                      >
                        注册
                      </v-btn>
                      <v-btn @click="clear" color="red" class="white--text">
                        清除
                      </v-btn>
                    </div>
                  </v-row>
                </form>
              </validation-observer>
            </v-card>
          </v-col>
        </v-row>
      </v-tab-item>
    </v-tabs-items>
  </v-sheet>
</template>

<script>
import { required, email, max, min, regex } from "vee-validate/dist/rules";
import {
  extend,
  ValidationObserver,
  ValidationProvider,
  setInteractionMode,
} from "vee-validate";
import { mapActions } from "vuex";

setInteractionMode("eager");

extend("required", {
  ...required,
  message: "{_field_}不能为空",
});

extend("max", {
  ...max,
  message: "{_field_}不能超过{length}个字符",
});

extend("min", {
  ...min,
  message: "{_field_}至少为{length}个字符",
});

extend("regex_username", {
  ...regex,
  message: "用户名不符合要求",
});

extend("regex_password", {
  ...regex,
  message: "密码必须且只能包含字母和数字",
});

extend("email", {
  ...email,
  message: "邮箱格式不正确",
});

export default {
  components: {
    ValidationProvider,
    ValidationObserver,
  },
  data: () => ({
    tab: null,
    form: {
      username: "",
      full_name: "",
      email: "",
      school: null,
      schools: ["计算机科学与技术学院", "人工智能学院", "中丹学院", "xxx学院"],
      password: "",
      showPassword: false,
      avatar: "",
    },
    error: {
      login: { showError: false, errorMsg: "" },
      register: { showError: false, errorMsg: "" },
    },
  }),

  methods: {
    ...mapActions(["register", "login"]),
    // 注册
    async register_form() {
      this.$refs.observer.validate();
      try {
        this.form.avatar =
          "https://ui-avatars.com/api/?background=5acaf2&color=fff&name=" +
          this.form.username;
        let err = await this.register(this.form);
        if (err === 11) {
          this.error.register.showError = true;
          this.error.register.errorMsg = "用户名已存在";
        } else {
          this.$router.push("/");
          this.error.register.showError = false;
        }
      } catch (error) {
        this.error.register.showError = true;
      }
    },
    // 登录
    async login_form() {
      const user = new FormData();
      user.append("username", this.form.username);
      user.append("password", this.form.password);
      try {
        let err = await this.login(user);
        if (err === 13) {
          this.error.login.showError = true;
          this.error.login.errorMsg = "用户名或密码错误";
        } else {
          this.$router.push("/");
          this.error.login.showError = false;
        }
      } catch (error) {
        this.error.login.showError = true;
      }
    },
    // 清除表单
    clear() {
      this.form.username = "";
      this.form.full_name = "";
      this.form.email = "";
      this.form.school = "";
      this.form.password = "";
      this.$refs.observer.reset();
    },
  },
};
</script>

<style scoped>
.my-tab-style {
  font-weight: bold;
  font-size: 1.1rem;
}
</style>